<template>
  <div class="project-modal">
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="基本信息" name="basic">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
          style="padding: 20px 40px"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="设为模板" prop="isTemplate">
            <el-switch v-model="formData.isTemplate" />
          </el-form-item>
          <el-form-item label="方案编号" prop="protocolNumber">
            <el-input v-model="formData.protocolNumber" placeholder="请输入方案编号" />
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input v-model="formData.version" placeholder="请输入版本号" />
          </el-form-item>
          <el-form-item label="版本日期" prop="versionDate">
            <el-date-picker
              v-model="formData.versionDate"
              type="date"
              placeholder="请选择版本日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="项目状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择项目状态" style="width: 100%">
              <el-option label="进行中" value="active" />
              <el-option label="已完成" value="completed" />
              <el-option label="已暂停" value="paused" />
            </el-select>
          </el-form-item>
          <el-form-item label="项目描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              rows="3"
              placeholder="请输入项目描述"
            />
          </el-form-item>
          <el-form-item label="创建时间" v-if="isEdit">
            <el-input
              v-model="formData.createTime"
              readonly
              placeholder="自动生成"
            />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <el-tab-pane label="导入" name="template" v-if="!isEdit">
        <div class="template-section">
          <div class="template-options">
            <el-radio-group v-model="templateOption">
              <!-- <el-radio value="none">不使用模板</el-radio> -->
              <el-radio value="fromProject">从项目中导入</el-radio>
              <el-radio value="fromTemplate">从模版中导入</el-radio>
            </el-radio-group>
          </div>
          
          <div v-if="templateOption === 'fromProject' || templateOption === 'fromTemplate'" class="template-selector-container">
            <ProjectTemplateSelector 
              v-model="selectedTemplate" 
              :filter-is-template="templateOption === 'fromTemplate'"
              :source-label="templateOption === 'fromTemplate' ? '模板' : '项目'"
            />
          </div>
          
          <div v-if="selectedTemplate" class="template-preview">
            <h4>已选择的模板：</h4>
            <div class="template-info">
              <p><strong>模板项目：</strong>{{ selectedTemplate.projectName }}</p>
              <p><strong>包含章节：</strong>{{ selectedTemplate.sections.length }} 个</p>
              <p><strong>包含表单：</strong>{{ getTotalForms() }} 个</p>
            </div>
            
            <div class="template-details">
              <el-collapse>
                <el-collapse-item 
                  v-for="section in selectedTemplate.sections" 
                  :key="section._id"
                  :title="`${section.name} (${section.forms?.length || 0} 个表单)`"
                >
                  <div class="section-forms">
                    <div v-for="form in section.forms" :key="form._id" class="form-item">
                      <span class="form-name">{{ form.name }}</span>
                      <span class="form-code">{{ form._id || form.id }}</span>
                      <span class="form-fields">{{ form.config?.fields?.length || 0 }} 个字段</span>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
            
            <div class="template-actions">
              <el-button @click="clearTemplate">清除模板</el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <div class="modal-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        {{ getConfirmButtonText() }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import ProjectTemplateSelector from './ProjectTemplateSelector.vue'

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close'])

const formRef = ref(null)
const activeTab = ref('basic')
const templateOption = ref('none')
const selectedTemplate = ref(null)
const loading = ref(false)

// 格式化当前日期为 YYYY-MM-DD 格式
const getCurrentDate = () => {
  const now = new Date()
  return now.toISOString().split('T')[0]
}

// 格式化创建时间显示
const formatCreateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const formData = ref({
  name: props.editData?.name || '',
  protocolNumber: props.editData?.protocolNumber || '',
  version: props.editData?.version || '1.0.0',
  versionDate: props.editData?.versionDate || getCurrentDate(),
  status: props.editData?.status || 'active',
  description: props.editData?.description || '',
  isTemplate: props.editData?.isTemplate || false,
  createTime: props.editData?.createTime ? formatCreateTime(props.editData.createTime) : ''
})

const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  protocolNumber: [{ required: true, message: '请输入方案编号', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  versionDate: [{ required: true, message: '请选择版本日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择项目状态', trigger: 'change' }]
}

// 监听模板选项变化
watch(templateOption, (newValue) => {
  if (newValue === 'none') {
    selectedTemplate.value = null
  }
})

// 模板相关方法
const clearTemplate = () => {
  selectedTemplate.value = null
  templateOption.value = 'none'
}

const getTotalForms = () => {
  if (!selectedTemplate.value) return 0
  return selectedTemplate.value.sections.reduce((total, section) => {
    return total + (section.forms?.length || 0)
  }, 0)
}

// 获取确认按钮文本
const getConfirmButtonText = () => {
  if (props.isEdit) {
    return '保存'
  }
  if (activeTab.value === 'template') {
    return '下一步'
  }
  return '创建项目'
}

// 确认提交
const handleConfirm = async () => {
  if (!formRef.value) return
  
  // 如果当前在模板设置标签页，先切换到基本信息标签页
  if (activeTab.value === 'template') {
    activeTab.value = 'basic'
    return
  }
  
  loading.value = true
  
  try {
    await formRef.value.validate((valid) => {
      if (valid) {
        // 提交数据时，不包含显示格式的创建时间
        const submitData = {
          name: formData.value.name,
          protocolNumber: formData.value.protocolNumber,
          version: formData.value.version,
          versionDate: formData.value.versionDate,
          status: formData.value.status,
          description: formData.value.description,
          isTemplate: formData.value.isTemplate
        }

        console.log('submitData', submitData)
        
        // 如果是编辑模式，保留原有的创建时间
        if (props.isEdit && props.editData?.createTime) {
          submitData.createTime = props.editData.createTime
        }
        
        // 如果选择了模板，添加模板信息和配置章节（fromProject/fromTemplate 都走模板导入）
        if (selectedTemplate.value && (templateOption.value === 'fromProject' || templateOption.value === 'fromTemplate')) {
          submitData.template = selectedTemplate.value
          console.log('selectedTemplate.value', selectedTemplate.value)
          
          // 将模板的 sections 转换为 configSections 格式
          if (selectedTemplate.value.sections && selectedTemplate.value.sections.length > 0) {
            submitData.configSections = selectedTemplate.value.sections.map((section, index) => ({
              sectionId: section._id,
              order: index + 1,
              config: {} // 默认为空配置
            }))
          }
        }
        
        console.log('提交数据:', submitData)
        emit('close', submitData)
      }
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('close')
}
</script>

<style scoped>
.project-modal {
  width: 100%;
}

.template-section {
  padding: 20px;
}

.template-options {
  margin-bottom: 20px;
}

.template-selector-container {
  margin-top: 20px;
}

.template-preview {
  margin-top: 20px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #f9f9f9;
}

.template-preview h4 {
  margin: 0 0 12px 0;
  color: #303133;
}

.template-info {
  margin-bottom: 16px;
}

.template-info p {
  margin: 4px 0;
  color: #606266;
}

.template-details {
  margin-bottom: 16px;
}

.section-forms {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.form-name {
  font-weight: 500;
  color: #303133;
}

.form-code {
  color: #606266;
  font-size: 12px;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 2px;
}

.form-fields {
  color: #909399;
  font-size: 12px;
  margin-left: auto;
}

.template-actions {
  display: flex;
  justify-content: flex-end;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-tabs__content) {
  padding: 0;
}
</style> 